import logging
from django.views.decorators.http import require_GET
from common.mg_core import mg
from common.utils.decorator import response_wrapper, validate_form
from common.utils.api import token_required
from common.cp.maestro import user_analysis_handler as handler
from common.utils.export import export_file
from common.permission.handler import process_resp_items, get_key_mapper
from .form import (
    ActiveAnalysisForm,
    RechargeStageAnalysisForm,
    PayAbilityAnalysisForm,
    NewUserAnalysis,
    NewUserStayAnalysis
)

_LOGGER = logging.getLogger(__name__)


@require_GET
@response_wrapper
@token_required
@validate_form(ActiveAnalysisForm)
def get_active_user_analysis(req, cleaned_data):
    merchant_name, role_id = req.merchant_name, req.merchant_role['id']
    index = req.es_index
    user_id = cleaned_data['user_id']
    chn_filter_list = cleaned_data['channel']
    sort_by = cleaned_data['sort_by'] or '-updated_at'
    time_range = cleaned_data['time_range']
    registered_time_range = cleaned_data['registered_time_range']
    size, page = cleaned_data['size'], cleaned_data['page']
    to_export_file = cleaned_data['to_export_file']
    disable_paginate = True if to_export_file else False
    analysis_result, total_count = handler.get_active_user_analysis_report(index, user_id=user_id,
                                                                           chn_filter_list=chn_filter_list,
                                                                           time_range=time_range,
                                                                           registered_time_range=registered_time_range,
                                                                           disable_paginate=disable_paginate,
                                                                           sort_by=sort_by, page=page, size=size
                                                                           )
    key_mapper = get_key_mapper(merchant_name, '4002', role_id)
    resp_items = process_resp_items(analysis_result, key_mapper)
    if to_export_file:
        return export_file(req, resp_items, key_mapper, file_name='active_user_analysis', maximum_row=50000)
    return dict(list=resp_items, total_count=total_count, key_mapper=key_mapper)


@require_GET
@response_wrapper
@token_required
@validate_form(PayAbilityAnalysisForm)
def get_pay_ability_analysis(req, cleaned_data):
    merchant_name = req.merchant_name
    role_id = req.merchant_role['id']
    time_range = cleaned_data['time_range']
    recharge_stage_list = cleaned_data['recharge_stage_list']
    chn_filter_list = cleaned_data['chn_filter_list']
    user_type = cleaned_data['user_type']
    sort_by = cleaned_data['sort_by'] or '-updated_at'
    size, page = cleaned_data['size'], cleaned_data['page']
    to_export_file = cleaned_data['to_export_file']
    condition = dict(updated_at={'$gte': time_range[0], '$lt': time_range[1]})
    condition['recharge_stage'] = {'$in': recharge_stage_list} if recharge_stage_list else 'all'
    condition['_chn'] = {'$in': chn_filter_list} if chn_filter_list else 'all'
    disable_paginate = False if not to_export_file else True
    user_reports, total_count = mg.get_report(merchant_name, 'user_pay_ability_report', condition,
                                              sort_key=sort_by, page=page, size=size,
                                              disable_paginate=disable_paginate, user_type=user_type)
    key_mapper = get_key_mapper(merchant_name, '4003', role_id, required_chn=True if chn_filter_list else False)
    resp_items = process_resp_items(user_reports, key_mapper)
    if to_export_file:
        return export_file(req, resp_items, key_mapper, file_name='recharge_stage_analysis')
    return dict(total_count=total_count, list=resp_items, key_mapper=key_mapper)


@require_GET
@response_wrapper
@token_required
@validate_form(RechargeStageAnalysisForm)
def get_recharge_stage_analysis(req, cleaned_data):
    merchant_name, role_id = req.merchant_name, req.merchant_role['id']
    time_range = cleaned_data['time_range']
    recharge_stage_list = cleaned_data['recharge_stage_list']
    sort_by = cleaned_data['sort_by'] or '-updated_at'
    user_type = cleaned_data['user_type']
    size, page = cleaned_data['size'], cleaned_data['page']
    to_export_file = cleaned_data['to_export_file']
    condition = dict(updated_at={'$gte': time_range[0], '$lt': time_range[1]})
    condition['recharge_stage'] = {'$in': recharge_stage_list} if recharge_stage_list else 'all'
    disable_paginate = False if not to_export_file else True
    user_reports, total_count = mg.get_report(merchant_name, 'user_recharge_stage_report', condition,
                                              sort_key=sort_by, page=page, size=size,
                                              disable_paginate=disable_paginate, user_type=user_type)
    key_mapper = get_key_mapper(merchant_name, '4004', role_id)
    resp_items = process_resp_items(user_reports, key_mapper)
    if to_export_file:
        return export_file(req, resp_items, key_mapper, file_name='recharge_stage_analysis')
    return dict(total_count=total_count, list=resp_items, key_mapper=key_mapper)


@require_GET
@response_wrapper
@token_required
@validate_form(NewUserAnalysis)
def get_new_user_analysis(req, cleaned_data):
    merchant_name, role_id = req.merchant_name, req.merchant_role['id']
    time_range = cleaned_data['time_range']
    chn_filter_list = cleaned_data['chn_filter_list']
    sort_by = cleaned_data['sort_by'] or '-updated_at'
    size, page = cleaned_data['size'], cleaned_data['page']
    to_export_file = cleaned_data['to_export_file']
    condition = dict(updated_at={'$gte': time_range[0], '$lt': time_range[1]})
    condition['_chn'] = {'$in': chn_filter_list} if chn_filter_list else 'all'
    disable_paginate = False if not to_export_file else True
    new_user_reports, total_count = mg.get_report(merchant_name, 'user_new_user_report', condition, sort_by,
                                                  page=page, size=size, disable_paginate=disable_paginate)
    key_mapper = get_key_mapper(merchant_name, '4005', role_id, required_chn=True if chn_filter_list else False)
    resp_items = process_resp_items(new_user_reports, key_mapper)
    if to_export_file:
        return export_file(req, resp_items, key_mapper, file_name='new_user_analysis')
    return dict(total_count=total_count, list=resp_items, key_mapper=key_mapper)


@require_GET
@response_wrapper
@token_required
@validate_form(NewUserStayAnalysis)
def get_new_user_stay_analysis(req, cleaned_data):
    merchant_name, role_id = req.merchant_name, req.merchant_role['id']
    time_range = cleaned_data['time_range']
    sort_by = cleaned_data['sort_by'] or '-updated_at'
    size, page = cleaned_data['size'], cleaned_data['page']
    to_export_file = cleaned_data['to_export_file']
    condition = dict(updated_at={'$gte': time_range[0], '$lt': time_range[1]})
    disable_paginate = False if not to_export_file else True
    new_user_reports, total_count = mg.get_report(merchant_name, 'user_new_user_stay_report', condition,
                                                  sort_key=sort_by, page=page, size=size,
                                                  disable_paginate=disable_paginate)
    key_mapper = get_key_mapper(merchant_name, '4006', role_id)
    resp_items = process_resp_items(new_user_reports, key_mapper)
    if to_export_file:
        return export_file(req, resp_items, key_mapper, file_name='new_user_stay_analysis')
    return dict(total_count=total_count, list=resp_items, key_mapper=key_mapper)
